auto.waitFor()

var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!")
    while (true) {
      var allow = text("允许").findOne(5000)
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!")
        allow.click()
        sleep(1000)
        thread.interrupt()
        break
      }
    }
  })
  sleep(1000)
  var result = launchApp(app_name)
  sleep(3000)
  thread.interrupt()
  return result
}

function task() {
  var 首页 = text('首页').findOne(20000)
  if (首页) {
    sleep(5000)
    var 确认领取 = text('确认领取').findOne(3000)
    if (确认领取) {
      确认领取.click()
    }
    var 点击领券 = text('点击领券').findOne(3000)
    if (点击领券) {
      点击领券.click()
    }
    var 确认领取 = text('确认领取').findOne(3000)
    if (确认领取) {
      确认领取.click()
    }
  }
}

function main() {
  let open_app = launchAppEnhance("欢乐兑U");
  if (open_app) {
    task()
  }
  else {
    toastLog("欢乐兑U打开失败，请确认是否安装并授权打开!");
  }
}

try {
  main();
} catch (error) {
  toastLog(error);
}

storage.put("script_running_status", "end");
